package org.gl.utils;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.gl.GlobalVariable;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;

/**
 * @author gl
 * @date 2012-11-13
 */
public class AndroidUtil {
	/**
	 * 鐢熸垚涓�釜AlertDialog 骞舵樉绀�
	 * 
	 * @param content
	 *            搴旇鏄竴涓毝灞炰簬activity鐨勪笂涓嬫枃 闈瀊aseContent or applicationContent
	 * @param message
	 *            鏄剧ず鐨勬秷鎭唴瀹�
	 * @param title
	 *            鏄剧ず鐨勬秷鎭爣棰�
	 * @param yesOnclickImp
	 *            涓�釜鎸変笅纭畾鎸夐挳鐨勫疄鐜颁簨浠�
	 */
	public static void genDialog(Context content, String message, String title,
			DialogInterface.OnClickListener yesOnclickImp) {
		new AlertDialog.Builder(content)
				.setMessage(message)
				.setPositiveButton("ok", yesOnclickImp)
				.setNegativeButton("cancel",
						new DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						}).setTitle(title).show();
	}

	/**
	 * 鍍忕礌杞�杈戝瘑搴�
	 * 
	 * @param px
	 * @return
	 */
	public static int pxToDip(float px) {
		final float scale = GlobalVariable.applicationContext.getResources()
				.getDisplayMetrics().density;
		DebugUtil.println("density" + scale);
		return (scale != 0) ? (int) (px / scale + 0.5f)
				: (int) (px / 1.5 + 0.5f);

	}

	/**
	 * 閫昏緫瀵嗗害杞儚绱�
	 * 
	 * @param dip
	 * @return
	 */
	public static int dipToPx(float dip) {
		final float scale = GlobalVariable.applicationContext.getResources()
				.getDisplayMetrics().density;
		DebugUtil.outToFile("density " + scale, null);
		return (scale != 0) ? (int) (dip * scale - 0.5f)
				: (int) (dip * 1.5 - 0.5f);
		// return int padding =
		// (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
		// 4,
		// GlobalVariable.applicationContext().getResources().getDisplayMetrics());
	}

	/**
	 * 妫�煡璁惧缃戠粶
	 * 
	 * @return
	 */
	public static boolean checkNetwork() {
		ConnectivityManager conn = (ConnectivityManager) GlobalVariable.applicationContext
				.getSystemService(Context.CONNECTIVITY_SERVICE);
		NetworkInfo net = conn.getActiveNetworkInfo();
		if (net != null && net.isConnected()) {
			return true;
		}
		return false;
	}

	/**
	 * 閫氳繃涓�釜24rgb瀛楄妭鏁扮粍鍒涘缓鍥剧墖骞朵繚瀛樹负鍥剧墖鏂囦欢
	 * 
	 * @param rgb24
	 * @param width
	 * @param height
	 * @param filename
	 * @return
	 */
	public static boolean creatPNG(byte rgb24[], int width, int height,
			String filename) {
		byte data[] = rgb24;
		try {
			Bitmap bitmap = creatBitmap(width, height, data);
			if (bitmap != null) {
				File file2 = new File(filename);
				OutputStream os = new FileOutputStream(file2);
				file2.createNewFile();
				bitmap.compress(CompressFormat.PNG, 100, os);
				bitmap.recycle();
			} else {
				System.out.println("瑙ｇ爜澶辫触");
			}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return true;
	}

	/**
	 * 閫氳繃涓�釜24rgb瀛楄妭鏁扮粍鍒涘缓涓�釜Bitmap
	 * 
	 * @param width
	 * @param height
	 * @param rgb24
	 * @return
	 */
	private static Bitmap creatBitmap(int width, int height, byte[] rgb24) {
		int Rgb[] = convertByteToColor(rgb24);
		Bitmap bitmap = Bitmap.createBitmap(Rgb, 0, width, width, height,
				Bitmap.Config.ARGB_8888);
		return bitmap;
	}

	/*
	 * 灏�4RGB鏁扮粍杞寲涓哄儚绱犳暟缁�
	 */
	public static int[] convertByteToColor(byte[] data) {
		int size = data.length;
		if (size == 0) {
			return null;
		}
		// 鐞嗚涓奷ata鐨勯暱搴﹀簲璇ユ槸3鐨勫�鏁帮紝杩欓噷鍋氫釜鍏煎
		int arg = 0;
		if (size % 3 != 0) {
			arg = 1;
		}

		int[] color = new int[size / 3 + arg];

		if (arg == 0) { // 姝ｅソ鏄�鐨勫�鏁�
			for (int i = 0; i < color.length; ++i) {

				color[i] = (data[i * 3] << 16 & 0x00FF0000)
						| (data[i * 3 + 1] << 8 & 0x0000FF00)
						| (data[i * 3 + 2] & 0x000000FF) | 0xFF000000;
			}
		} else { // 涓嶆槸3鐨勫�鏁�
			for (int i = 0; i < color.length - 1; ++i) {
				color[i] = (data[i * 3] << 16 & 0x00FF0000)
						| (data[i * 3 + 1] << 8 & 0x0000FF00)
						| (data[i * 3 + 2] & 0x000000FF) | 0xFF000000;
			}

			color[color.length - 1] = 0xFF000000; // 鏈�悗涓�釜鍍忕礌鐢ㄩ粦鑹插～鍏�
		}

		return color;
	}

	/**
	 * 鍦╳ifi鏈紑鍚姸鎬佷笅锛屼粛鐒跺彲浠ヨ幏鍙朚AC鍦板潃锛屼絾鏄疘P鍦板潃蹇呴』鍦ㄥ凡杩炴帴鐘舵�涓嬪惁鍒欎负0
	 * 
	 * @return
	 */
	public static String getLocalIP() {
		String macAddress = null, ip = null;
		WifiManager wifiMgr = (WifiManager) GlobalVariable.applicationContext
				.getSystemService(Context.WIFI_SERVICE);
		WifiInfo info = (null == wifiMgr ? null : wifiMgr.getConnectionInfo());
		if (null != info) {
			macAddress = info.getMacAddress();
			ip = int2ip(info.getIpAddress());
		}
		System.out.println("mac:" + macAddress + ",ip:" + ip);
		return ip;

	}

	public static String int2ip(long ipInt) {
		StringBuilder sb = new StringBuilder();
		sb.append(ipInt & 0xFF).append(".");
		sb.append((ipInt >> 8) & 0xFF).append(".");
		sb.append((ipInt >> 16) & 0xFF).append(".");
		sb.append((ipInt >> 24) & 0xFF);
		return sb.toString();
	}

	public static SharedPreferences getConfigSharedPreferences() {
		SharedPreferences configSharedPreferences = GlobalVariable.applicationContext
				.getSharedPreferences(AppConfig.SharedPreferencesXML_NAME, 0);
		return configSharedPreferences;
	}

	/**
	 * save account to sharedPreferences
	 * 
	 * @param account
	 * @param password
	 */
	public static void saveAccountPassword(String account, String password) {
		SharedPreferences configSharedPreferences = getConfigSharedPreferences();
		Editor edit = configSharedPreferences.edit();
		edit.putString(AppConfig.ACCOUNT, account);
		edit.putString(AppConfig.PASSWORD, password);
		edit.commit();
	}

	/**
	 * get account from sharedPreferences
	 * 
	 * @return String[],String[0] ==account,String[1] =password; </p> default
	 *         return"",""
	 */
	public static String[] getAccountPassword() {
		SharedPreferences configSharedPreferences = getConfigSharedPreferences();
		String[] s = new String[2];
		s[0] = configSharedPreferences.getString(AppConfig.ACCOUNT, "");
		s[1] = configSharedPreferences.getString(AppConfig.PASSWORD, "");
		return s;
	}

	public static String getServerIPConfig() {
		SharedPreferences configSharedPreferences = getConfigSharedPreferences();
		return configSharedPreferences.getString(AppConfig.Secver_IP,
				"192.168.0.156");
	}

	public static boolean setServerIPConfig(String ip) {
		SharedPreferences configSharedPreferences = getConfigSharedPreferences();
		Editor edit = configSharedPreferences.edit();
		edit.putString(AppConfig.Secver_IP, ip);
		return edit.commit();
	}
	public static String getServerPortConfig() {
		SharedPreferences configSharedPreferences = getConfigSharedPreferences();
		return configSharedPreferences.getString(AppConfig.Secver_PORT,
				"80");
	}
	
	public static boolean setServerPortConfig(String prot) {
		SharedPreferences configSharedPreferences = getConfigSharedPreferences();
		Editor edit = configSharedPreferences.edit();
		edit.putString(AppConfig.Secver_PORT, prot);
		return edit.commit();
	}
	/**
	 * 该值被调用取值后 会立刻被设置为false
	 * @return
	 */
	public static boolean isFirstUseApp() {
		SharedPreferences configSharedPreferences = getConfigSharedPreferences();
		boolean is = configSharedPreferences.getBoolean(AppConfig.ISFIRSTUSEAPP, true);
		setFirstUseApp(false);
		return is;
	}

	public static boolean setFirstUseApp(boolean is) {
		SharedPreferences configSharedPreferences = getConfigSharedPreferences();
		Editor edit = configSharedPreferences.edit();
		edit.putBoolean(AppConfig.ISFIRSTUSEAPP, is);
		return edit.commit();
	}

}
